package com.yunatt.uitls;


import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidParameterSpecException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class WXBizDataCrypt {
    private String appId;
    private String appSecret;

    public WXBizDataCrypt(String appId, String appSecret) {
        this.appId = appId;
        this.appSecret = appSecret;
    }

    public String decryptData(String encryptedData, String iv) {
        byte[] dataByte = Base64.getDecoder().decode(encryptedData);
        byte[] keyByte;
        byte[] ivByte;
        String jsonStr;
        try {
            keyByte = Base64.getDecoder().decode(this.appSecret);
            ivByte = Base64.getDecoder().decode(iv);
            jsonStr = new String(decrypt(dataByte, keyByte, ivByte), StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonStr;
    }

    private byte[] decrypt(byte[] data, byte[] key, byte[] iv) {
        try {
            AlgorithmParameters alg = AlgorithmParameters.getInstance("AES");
            alg.init(new IvParameterSpec(iv));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), alg);
            return cipher.doFinal(data);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
                 InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException |
                 InvalidParameterSpecException e) {
            throw new RuntimeException(e);
        }
    }
}